package com.xiaxueqi.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.xiaxueqi.service.UploadService;

public class UploadServiceImpl implements UploadService {

	private final static char SEPARATOR = File.separatorChar;

	public String upload(File uploadFile, String fileName, String savePath)
			throws Exception {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String day = format.format(new Date());
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
		String desPath = ServletActionContext.getServletContext().getRealPath(
				savePath)
				+ SEPARATOR + fileType + SEPARATOR + day + "_" + fileName;
		File desFile = new File(desPath);
		copy(uploadFile, desFile);

		String filePath = savePath + "/" + fileType + "/" + day + "_"
				+ fileName;

		return filePath;
	}

	public String[] upload(File[] uploadFiles, String[] fileNames,
			String savePath) throws Exception {
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String day = format.format(new Date());
		String[] filePath = new String[uploadFiles.length];
		for (int i = 0; i < uploadFiles.length; i++) {
			String fileType = fileNames[i].substring(fileNames[i]
					.lastIndexOf(".") + 1);
			String desPath = ServletActionContext.getServletContext()
					.getRealPath(savePath)
					+ SEPARATOR
					+ fileType
					+ SEPARATOR
					+ day
					+ "_"
					+ i
					+ "_"
					+ fileNames[i];

			filePath[i] = savePath + "/" + fileType + "/" + day + "_" + i + "_"
					+ fileNames[i];

			File desFile = new File(desPath);
			copy(uploadFiles[i], desFile);
		}

		return filePath;
	}

	private void copy(File src, File des) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(des),
					BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int legth = 0;
			while ((legth = in.read(buffer)) > 0) {
				out.write(buffer, 0, legth);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
